package com.zixun.service.Impl;

import com.zixun.model.Bill;
import com.zixun.repository.BillRepository;
import com.zixun.service.BillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Basil on 16/8/27.
 */
@Service
public class BillServiceImpl implements BillService{

    @Autowired
    private BillRepository billRepository;

    @Override
    public Page<Bill> findByUserIdPage(final Integer userId, final Integer billType,Integer pageIndex, Integer countPerPage) {
        Specification<Bill> billSpecification = new Specification<Bill>() {
            @Override
            public Predicate toPredicate(Root<Bill> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                Path<Integer> $userId =root.get("userId");
                Predicate _userId = cb.equal($userId,userId);
                predicates.add(_userId);
                Path<Integer> $billType =root.get("billType");
                Predicate _billType =cb.equal($billType,billType);
                predicates.add(_billType);
                return cb.and(predicates
                        .toArray(new Predicate[] {}));
            }
        };
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(pageIndex-1,countPerPage,sort);
        return billRepository.findAll(billSpecification,pageable);
    }
}
